package combine.order.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import combine.order.impl.dao.ibatis.OrderDaoIbatis;
import combine.order.impl.dao.ibatis.OrderItemDaoIbatis;
import combine.order.model.DataBase;
import combine.order.model.FinishedProduct;
import combine.order.model.Order;
import combine.order.model.OrderItem;
import combine.order.model.OrderManger;

@Service
public class OrderManagerImpl implements OrderManger {

	@Autowired
	private OrderDaoIbatis orderDaoIbatis = new OrderDaoIbatis();

	@Autowired
	private OrderItemDaoIbatis orderItemDaoIbatis = new OrderItemDaoIbatis();

	// @Override
	// public void insertOrder(Order order) throws Exception {
	// orderDaoIbatis.insert(order);
	// }

	@Override
	public long insertOrder(long orderId, OrderItem item) throws Exception {
		if (orderId <= 0) {
			Order order = new Order();
			order.setOrderCreateTime(System.currentTimeMillis());
			order.setOrderCreatorId(1);
			order.setOrderCreatorName("admin");
			order.setOrderLastModifyTime(System.currentTimeMillis());
			// orderId = (Long)orderDaoIbatis.insert(order);
			DataBase.orders.add(order);
			orderId = DataBase.orders.size();
			order.setOrderId(orderId);
		}
		item.setOrderId(orderId);
		item.setOrderItemId(DataBase.orderItems.size());
		item.setFinishedProduct(DataBase.finishedProducts.get((int) item
				.getFinishProductId() - 1));
		item.setProductColor(DataBase.productColors.get((int)item.getOrderColorId()-1));
		orderItemDaoIbatis.insert(item);
		return orderId;
	}

	@Override
	public List<Order> findUnFinishOrder() throws Exception {
		List<Order> orders = orderDaoIbatis.findOrderDaoByStatus(false);
		for (Order order : orders) {
			order.setItem(orderItemDaoIbatis.findOrderItemByOrderId(order
					.getOrderId()));
		}
		return orders;
	}

	@Override
	public Order findOrderByOrderId(long orderId) throws Exception {
		Order mOrder = null;
		for (Order order : DataBase.orders) {
			if (order.getOrderId() == orderId) {
				mOrder = order;
				break;
			}
		}
		return mOrder;
	}

	@Override
	public List<OrderItem> findItemsByOrderId(long orderId) throws Exception {
		List<OrderItem> items = new ArrayList<OrderItem>();
		for (OrderItem item : DataBase.orderItems) {
			if (item.getOrderId() == orderId) {
				items.add(item);
			}
		}
		return items;
	}

}
